// app.js
import {createStoreBindings} from 'mobx-miniprogram-bindings'
import {store} from './store/sotre'

App({
  async getUserInfo(){
    // 获取openid
    const res = await wx.cloud.callFunction({
      name: 'get_openId'
    })
    // 获取对应用户数据
    const db = wx.cloud.database()
    const userData = await db.collection('userInfo').where({
      openid: res.result.openid
    }).get()

    // 若数据库有该用户则将信息同步页面
    if(userData.data.length > 0){
      console.log('get UserInfo');
      this.globalData.userInfo = userData.data[0]
      this.globalData.isUserInfo = true
    }
  }, 
  // 获取系统底部导航条高度
  systemTabBar(){
    const systemInfo  = wx.getSystemInfoSync()
    const height = systemInfo.screenHeight - systemInfo.safeArea.bottom
    this.globalData.systemHeight = height
  },
  /**
   * 当小程序初始化完成时，会触发 onLaunch（全局只触发一次）
   */
  onLaunch: function () {
    wx.cloud.init({
      env: 'ax-cloud-6gs71h36ef44f6e6',
      traceUser: true
    })

    this.storeBindings = createStoreBindings(this, {
      store,
      actions: ['updateCheckNum']
    })

    // 获取商品中为true的个数
    const obj = wx.getStorageSync('goodsList') || []
    const countTrue = obj.reduce((count, item) => {
      return item.isSelected ? count + 1 : count;
    }, 0)
    this.updateCheckNum(countTrue)
    // 加载字体包
    wx.loadFontFace({
      global: true,
      family: 'price',
      source: 'url("https://6178-ax-cloud-6gs71h36ef44f6e6-1311849331.tcb.qcloud.la/a20240109/din-bold-2.ttf?sign=2b2c03219a88b7d856f6997a64b5a7d6&t=1707131747")'
    })
    this.systemTabBar()
    this.getUserInfo()
    
  },

  /**
   * 当小程序启动，或从后台进入前台显示，会触发 onShow
   */
  onShow: function (options) {
    
  },

  /**
   * 当小程序从前台进入后台，会触发 onHide
   */
  onHide: function () {
    
  },

  /**
   * 当小程序发生脚本错误，或者 api 调用失败时，会触发 onError 并带上错误信息
   */
  onError: function (msg) {
    
  },
  globalData: {
    isShowDia: true, // 
    goodsList: null, // 
    systemHeight: 0, // 系统导航栏高度
    settleGoods: [], // 
    userInfo: {
      avatarUrl: 'cloud://ax-cloud-6gs71h36ef44f6e6.6178-ax-cloud-6gs71h36ef44f6e6-1311849331/a20240109/logo.png', 
      nickname: '注册/登录'
    } , // 用户信息
    isUserInfo: false, // 是否存在用户信息

  }
})

